package com.nsproject;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;

import com.nibiru.nxrnativeengine.INSEnginePlayerEvents;
import com.nibiru.nxrnativeengine.NSEnginePlayer;
import com.nibiru.nxrnativeengine.NXREngineNativeApi;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NSMainActivity extends Activity implements INSEnginePlayerEvents {

    protected NSEnginePlayer mNSPlayer;//尽量不要修改该变量名称！

    final static String TAG = "NSMainActivity";

    @Override protected void onCreate(Bundle savedInstanceState)
    {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        handlePermissions();

        mNSPlayer = new NSEnginePlayer(this, this);
        setContentView(mNSPlayer);
        mNSPlayer.requestFocus();
    }


    @Override protected void onNewIntent(Intent intent)
    {
        setIntent(intent);
        if( mNSPlayer != null )
        {
            mNSPlayer.newIntent(intent);
        }
    }

    @Override protected void onDestroy ()
    {
        if( mNSPlayer != null ) {
            mNSPlayer.destroy();
        }
        super.onDestroy();
    }

    @Override protected void onStop()
    {
	    if (NXREngineNativeApi.isMultiWindowMode(this) && mNSPlayer != null)
        {
            mNSPlayer.pause();
        }
        super.onStop();

    }

    @Override protected void onStart()
    {
        super.onStart();

        if (NXREngineNativeApi.isMultiWindowMode(this) && mNSPlayer != null)
        {
            mNSPlayer.resume();
        }

    }

    @Override protected void onPause()
    {
	    if (!NXREngineNativeApi.isMultiWindowMode(this) && mNSPlayer != null )
        {
            mNSPlayer.pause();
        }
		
        super.onPause();


    }

    @Override protected void onResume()
    {
        super.onResume();

        if (!NXREngineNativeApi.isMultiWindowMode(this) && mNSPlayer != null)
        {
            mNSPlayer.resume();
        }

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if( mNSPlayer != null && mNSPlayer.injectEvent(event) )
        {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if( mNSPlayer != null && mNSPlayer.injectEvent(ev) )
        {
            return true;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean dispatchGenericMotionEvent(MotionEvent ev) {
        if( mNSPlayer != null && mNSPlayer.injectEvent(ev) )
        {
            return true;
        }
        return super.dispatchGenericMotionEvent(ev);
    }

    //如需要其他权限，添加在该列表中，统一申请
    private String[] defaultPermissionList = new String[]
        {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
        };

    protected String[] getRequirePermissions()
    {
        return new String[0];
    }

    private String[] getPermissionNames()
    {
        List<String> list = new ArrayList<>();
        for( String permission : defaultPermissionList )
        {
            list.add(permission);
        }

        final String[] customList = getRequirePermissions();
        if( customList != null )
        {
            for( String permissionCustom : customList ) {
                if( !list.contains(permissionCustom) )
                {
                    list.add(permissionCustom);
                }
            }
        }

        String[] result = new String[list.size()];
        list.toArray(result);
        return result;
    }


    void handlePermissions()
    {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            String[] permissionList = getPermissionNames();
            Log.d(TAG, "requestPermissions.SDK." + Build.VERSION.SDK_INT+", permissions: "+ Arrays.toString(permissionList));
            final int permissionCount = permissionList.length;
            PackageManager packageManager = this.getPackageManager();
            String packageName = this.getPackageName();

            ArrayList<String> newPermissionList = new ArrayList<>();
            for (int i = 0; i < permissionCount; i++) {
                int result = packageManager.checkPermission(
                    permissionList[i], packageName);
                if(result != PackageManager.PERMISSION_GRANTED)
                {
                    newPermissionList.add(permissionList[i]);
                    Log.d(TAG, "NEED GRANT " + permissionList[i]);
                }
            }

            if(newPermissionList.size() > 0) {
                String[] array =  newPermissionList.toArray(new String[newPermissionList.size()]);
                requestPermissions(array, NXREngineNativeApi.PERMISSION_REQUEST_CODE);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        Log.d(TAG, "onRequestPermissionsResult:" + requestCode + "," + Arrays.toString(permissions)
            + "," + Arrays.toString(grantResults));
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        Log.d(TAG , "onActivityResult:" + requestCode + "," + resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        if( mNSPlayer != null )
        {
            mNSPlayer.notifyActivityResult(requestCode, resultCode, data);
        }

    }

    @Override
    public void onNSEnginePlayerRequestQuit() {
        if( !isFinishing() ) {
            finish();
        }

    }

    @Override
    public void onNSEnginePlayerDestroyed() {

    }

    @Override
    public void onNSEnginePlayerQuitted() {
        if( !NXREngineNativeApi.bEnableReuse )
        {
			Log.d(TAG, "onNSEnginePlayerQuitted: kill process!");
            Process.killProcess(Process.myPid());
        }
    }
}
